// pages/seller/index.js
const app = getApp();

let req = require('../../utils/request.js');
let api = require('../../utils/api.js');
let area = require('../../utils/area.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    checked: '',
    phoneNumber: '',
    codeMsg: '获取验证码',
    code: '',
    iscountingDown: false,
    'uploadedPic': {
      'license': 'http://or0s8028r.bkt.clouddn.com/%E4%B8%8A%E4%BC%A0.png',
      'show': [
        'http://or0s8028r.bkt.clouddn.com/%E4%B8%8A%E4%BC%A0.png'
      ]
    },
    index: 0,
    area: '+86 中国大陆',
    disabled: {
      step_1: 'disabled',
      step_2: 'disabled',
      step_3: 'disabled',
      step_4: 'disabled'
    },
    input_data: {
      seller_name: '',
      seller_person: '',
      seller_license: '',
      seller_address: '',
      seller_phone: '',
      seller_fixed: '',
      seller_license_pic: '',
      seller_show_pic: ''
    }
  },
  onLoad: function (options) {
    var _this = this,
      area_arr = area.phone_reg,
      reg = [], areas = [], area_code = []

    //获取地区信息
    for (var i in area_arr) {
      var exploded_area_key = i.split('-')
      areas.push(exploded_area_key[1])
      area_code.push(exploded_area_key[2])
      reg.push(area_arr[i])
    }

    _this.setData({ reg: reg, areas: areas, area_code: area_code });
  },
  onReady: function () {},
  onShow: function () {},
  onHide: function () {},
  onUnload: function () {},
  onPullDownRefresh: function () {},
  onReachBottom: function () {},
  onShareAppMessage: function () {
  
  },
  //开始流程
  start() {
    this.setData({'step_1': 'hide'});
  },

  //检查输入
  checkInput(e) {
    var _this = this,
        value = e.detail.value,
        index = e.currentTarget.dataset.index,
        data = {}
    switch(index) {
      case '0':
        data['input_data.seller_name'] = value
        break;
      case '1':
        data['input_data.seller_person'] = value
        break;
      case '2':
        data['input_data.seller_license'] = value
        break;
      case '3':
        data['input_data.seller_address'] = value
        break;
      case '4':
        data['input_data.seller_fixed'] = value
        break;

    }
    _this.setData(data)

    var input_data = _this.data.input_data

    //第一步用户输入检测
    //TODO 还需要更精细的检测
    input_data.seller_name && input_data.seller_person && 
      input_data.seller_license && input_data.seller_address 
        ? _this.setData({ 'disabled.step_1': '' }) : _this.setData({ 'disabled.step_1': 'disabled' });    
    //第二步用户输入检测
    input_data.seller_phone && input_data.seller_fixed 
      ? _this.setData({ 'disabled.step_2': '' }) : _this.setData({ 'disabled.step_2': 'disabled' });

  },
  go(e) {
    var _this = this,
        index = e.currentTarget.dataset.index,
        data = {}

    switch(index) {
      case '0':
        data['step_2'] = 'hide'
        break;
      case '1':
        data['step_3'] = 'hide'
        break;
      case '2':
        data['step_4'] = 'hide'
        break;
      case '3':   //完成
        data['input_data.seller_token'] = app.globalData.userInfo.user_token
        _this.setData(data);

        var form_data = _this.data.input_data
        
        wx.showLoading({
          title: 'loading',
        })

        //提交资料
        req.request(
          api.apply,
          {
            method: 'POST',
            data: form_data
          },
          function(res) {
            wx.hideLoading();
            var result = res.data

            wx.showToast({
              title: result.msg,
              icon: 'none',
              duration: 2000
            })

            if (result.status == 1) {
              wx.getStorage({
                key: 'userInfo',
                success: function(res) {
                  res = res.data
                  res.user_status = 2

                  wx.setStorageSync('userInfo', res)
                  app.globalData.userInfo.user_status = 2
                  setTimeout(function () {
                    wx.redirectTo({
                      url: '/pages/seller/person',
                    })
                  }, 2500)
                },
              })
              
            }

          }
        )
        break;
    }

    _this.setData(data);
  },
  checkLegal(e) {
    var _this = this,
      index = _this.data.index,
      reg = _this.data.reg[index],
      area_code = _this.data.area_code[index],
      val = '+' + area_code + e.detail.value,
      data = {},
      isLegal = reg.test(val);
    if (isLegal && !_this.data.isCountingDown) {
      data['checked'] = 'checked';
      data['phoneNumber'] = val;
      data['input_data.seller_phone'] = val
    } else {
      data['checked'] = '';
      data['phoneNumber'] = val;
      data['input_data.seller_phone'] = val
    }
    _this.setData(data);

    //检查是否可以提交表单
    if (isLegal && _this.data.code == _this.data.currentCode && _this.data.input_data.seller_fixed) 
      _this.setData({ 'disabled.step_2': '' });
    else _this.setData({ 'disabled.step_2': 'disabled' });

  },
  getCode() {
    var _this = this,
      checked = _this.data.checked,
      index = _this.data.index,
      reg = _this.data.reg[index],
      time = 59,
      f = null
    
    
    if (checked == 'checked' && !_this.data.isCountingDown) {
      wx.showLoading({
        title: '发送中',
      })
      
      //TODO 发起网络请求，请求验证码
      var getPhoneCode = api.getPhoneCode
      req.request(
        getPhoneCode,
        {
          method: 'POST', data: {
            'phone': _this.data.phoneNumber
          }
        },
        function (res) {
          wx.hideLoading();
          var result = res.data

          //提示
          wx.showToast({
            title: result.msg,
            icon: 'none',
            duration: 2000
          });

          if (result.status == 1) {
            //将正确的码赋值到page
            _this.setData({ currentCode: result.code });
          }

          //分钟级流控
          f = setInterval(function () {
            _this.setData({
              codeMsg: time + 's后重发',
              checked: '',
              isCountingDown: true
            });
            if (time < 0) {
              var data = {};
              clearInterval(f);
              data['codeMsg'] = '重新发送';
              data['isCountingDown'] = false;

              if (reg.test(_this.data.phoneNumber)) {
                data['checked'] = 'checked';
              }
              _this.setData(data);
            }
            time--;
          }, 1000);
        }
      );
    }
  },
  checkCode(e) {
    //验证所有输入框是否都已输入且合法
    var code = e.detail.value,
      _this = this,
      phone = _this.data.phoneNumber,
      index = _this.data.index,
      reg = _this.data.reg[index],
      currentCode = _this.data.currentCode
    _this.setData({ code: code });
    if (code == currentCode && reg.test(phone) && _this.data.input_data.seller_fixed)
      _this.setData({ 'disabled.step_2': '' });
    else
      _this.setData({ 'disabled.step_2': 'disabled' });

  },
  //选择图片并上传
  uploadLicense() {
    var _this = this
    wx.chooseImage({
      count: 1,
      success: function (res) {
        wx.showLoading({
          title: '正在上传',
        })
        var file = res.tempFilePaths;
        req.upload(
          api.uploadPic,
          {
            filePath: file[0], 
            name: 'file'
          },
          function(res) {
            wx.hideLoading();
            var result = JSON.parse(res.data);
            wx.showToast({
              title: result.msg,
              icon: 'none',
              duration: 2000
            })
            
            if (result.code > 0) {
              _this.setData({ 'uploadedPic.license': result.pic_path, 'input_data.seller_license_pic': result.pic_path,'disabled.step_3': '' });
            }
          }
        );
        
      },
    })
  },
  uploadShow() {
    var _this = this
    wx.chooseImage({
      success: function (res) {
        wx.showLoading({
          title: '正在上传',
        })
        var file = res.tempFilePaths,
            length = res.tempFilePaths.length 
        req.uploadMulti(
          api.uploadPic,
          {
            filePath: file,
            name: 'file'
          },
          0, 0, 0, length,
          function (res, index) {
            if (index == length) {
              wx.hideLoading();
            }
            var result = JSON.parse(res.data);
            
            if (result.code > 0) {
              var data = {},
                  uploadedPic = _this.data.uploadedPic,
                  uploadedShow = _this.data.input_data.seller_show_pic
              uploadedPic['show'][index] = result.pic_path
              data['input_data.seller_show_pic'] = uploadedShow + result.pic_path + ';'
              data['disabled.step_4'] = ''
              data['uploadedPic'] = uploadedPic
              _this.setData(data)
            }
          }
        );

      },
    })
  },
  selectArea(e) {
    var _this = this,
    index = e.detail.value,
    areas = _this.data.areas,
    area_code = _this.data.area_code,
    area = '+' + area_code[index] + '  ' + areas[index]
    
    _this.setData({ area: area, index: index })
  },
  declares() {
    wx.navigateTo({
      url: '/pages/index/declares?id=2',
    })
  }
})